package com.shawn.mobliesafe;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.util.IOUtils;
import com.shawn.utils.StreamUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class SplashActivity extends AppCompatActivity {

    private static final int MSG_ENTER_HOME = 0;
    private static final int MSG_UPDATE_DIALOG = 1;
    private static final int MSG_SERVER_ERROR = 2;
    private static final int MSG_URL_ERROR = 3;
    private static final int MSG_IO_ERROR = 4;
    private static final int MSG_JSON_ERROR = 5;

    private TextView tv_splash_version;
    private ProgressBar sb_splash_update;
    private String code;
    private String apkurl;
    private JSONObject jsonObject;
    private String des;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case  MSG_UPDATE_DIALOG:
                    showdialog();
                    break;
                case MSG_ENTER_HOME:
                    enterHome();
                    break;
                case MSG_SERVER_ERROR:
                    //连接失败,服务器出现异常
                    Toast.makeText(getApplicationContext(), "服务器异常", Toast.LENGTH_SHORT).show();
                    enterHome();
                    break;
                case MSG_IO_ERROR:
                    Toast.makeText(getApplicationContext(), "亲,网络没有连接..", Toast.LENGTH_SHORT).show();
                    enterHome();
                    break;
                case MSG_URL_ERROR:
                    //方便我们后期定位异常
                    Toast.makeText(getApplicationContext(), "错误号:"+MSG_URL_ERROR, Toast.LENGTH_SHORT).show();
                    enterHome();
                    break;
                case MSG_JSON_ERROR:
                    Toast.makeText(getApplicationContext(), "错误号:"+MSG_JSON_ERROR, Toast.LENGTH_SHORT).show();
                    enterHome();
                    break;
            }
        }
    };
    private String targetPath;
    private SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        sp = getSharedPreferences("config",MODE_PRIVATE);
        tv_splash_version = (TextView)findViewById(R.id.tv_splash_version);
        tv_splash_version.setText("版本号：" + getVersionName());
        sb_splash_update = (ProgressBar)findViewById(R.id.sb_splash_update);
        
        if(sp.getBoolean("update",true)) {
            update();
        }else {
            new Thread(){
                private int startTime;
                @Override
                public void run() {
                    startTime = (int)System.currentTimeMillis();
                    copyDb();
                    int endTime = (int)System.currentTimeMillis();
                    int dTime = endTime - startTime;
                    if(dTime < 2000) {
                        SystemClock.sleep(2000 - dTime);
                    }
                    enterHome();
                }
            }.start();
        }

        shortcut();
    }

    /**
     * 创建快捷方式
     */
    private void shortcut() {
        // 给桌面发送一个广播
        Intent intent = new Intent(
                "com.android.launcher.action.INSTALL_SHORTCUT");
        // 设置属性
        // 设置快捷方式名称
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "手机卫士");
        //不允许重复创建
        intent.putExtra("duplicate", false);

        // 设置快捷方式的图标
        Bitmap value = BitmapFactory.decodeResource(getResources(),
                R.mipmap.ic_launcher);
        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, value);
        // 设置快捷方式执行的操作
        Intent intent2 = new Intent();
        intent2.setAction("com.shawn.mobliesafe.home");
        intent2.addCategory("android.intent.category.DEFAULT");
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent2);
        sendBroadcast(intent);
    }

    private void copyDb() {
        File file = new File(getFilesDir(),"address.db");
        if(!file.exists()) {
            AssetManager am = getAssets();
            InputStream in = null;
            FileOutputStream fos = null;
            try {
                in = am.open("address.db");
                fos = new FileOutputStream(file);
                byte[] bytes = new byte[1024];
                int len = -1;
                while((len=in.read(bytes))!=-1) {
                    fos.write(bytes,0,len);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(fos);
            }
        }
    }

    private void showdialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);//设置对话框不能消失
        builder.setTitle("新版本：" + code)
                .setIcon(R.mipmap.ic_launcher)
                .setMessage(des)
                .setPositiveButton("升级", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        download();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        enterHome();
                    }
                })
                .show();
    }

    private void download() {
        HttpUtils httpUtils = new HttpUtils();
        String filePath = getExternalFilesDir(null).getAbsolutePath();
        targetPath = filePath + "/mobliesafe.apk";
        //判断SD卡是否挂载
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            httpUtils.download(apkurl, targetPath, new RequestCallBack<File>() {

                @Override
                public void onSuccess(ResponseInfo<File> responseInfo) {
                    installAPK();
                }
                @Override
                public void onFailure(HttpException e, String s) {
                }

                //显示当前下载进度操作
                //total : 下载总进度
                //current : 下载的当前进度
                //isUploading : 是否支持断点续传
                @Override
                public void onLoading(long total, long current, boolean isUploading) {
                    super.onLoading(total, current, isUploading);
                    sb_splash_update.setVisibility(View.VISIBLE);
                    sb_splash_update.setMax((int)total);
                    sb_splash_update.setProgress((int)current);
                }
            });
        }else {
            Toast.makeText(this,"亲，请确定插入SD卡",Toast.LENGTH_SHORT);
        }
    }

    private void installAPK() {
        /**
         *  <intent-filter>
         <action android:name="android.intent.action.VIEW" />
         <category android:name="android.intent.category.DEFAULT" />
         <data android:scheme="content" /> //content : 从内容提供者中获取数据  content://
         <data android:scheme="file" /> // file : 从文件中获取数据
         <data android:mimeType="application/vnd.android.package-archive" />
         </intent-filter>
         */
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(Uri.fromFile(new File(targetPath)),"application/vnd.android.package-archive");
        //在当前activity退出的时候,会调用之前的activity的onActivityResult方法
        //requestCode : 请求码,用来标示是从哪个activity跳转过来
        startActivityForResult(intent,0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        enterHome();
    }

    private void enterHome() {
        Intent intent = new Intent(this,HomeActivity.class);
        startActivity(intent);
        finish();
    }




    private void update() {
        new Thread(){

            private int startTime;
            @Override
            public void run() {
                Message message = Message.obtain();
                startTime = (int)System.currentTimeMillis();
                String path = "http://192.168.1.104:8080/updateinfo.html";
                try {
                    URL url = new URL(path);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(5000);
                    connection.connect();
                    int responseCode = connection.getResponseCode();
                    if(responseCode == 200) {
                        InputStream is = connection.getInputStream();
                        String json = StreamUtil.parserStreamUtil(is);
                        jsonObject = new JSONObject(json);

                        code = jsonObject.getString("code");
                        apkurl = jsonObject.getString("apkurl");
                        des = jsonObject.getString("des");
                        if(code.equals(getVersionName())) {
                            message.what = MSG_ENTER_HOME;
                        }else{
                            message.what = MSG_UPDATE_DIALOG;
                        }
                    }else{
                        message.what = MSG_SERVER_ERROR;
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                    message.what = MSG_URL_ERROR;
                } catch (IOException e) {
                    e.printStackTrace();
                    message.what = MSG_IO_ERROR;
                } catch (JSONException e) {
                    message.what = MSG_JSON_ERROR;
                    e.printStackTrace();
                }finally {
                    int endTime = (int)System.currentTimeMillis();
                    int dTime = endTime - startTime;
                    if(dTime < 2000) {
                        SystemClock.sleep(2000 - dTime);
                    }
                    handler.sendMessage(message);
                }
            }
        }.start();
    }

    private String getVersionName(){
        PackageManager pm = getPackageManager();
        try {
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(),0);
            String versionName = packageInfo.versionName;
            return versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

}
